# coding=utf-8
__author__ = 'golsee'

from flask import flash, redirect, request, url_for
from .extensions import csrf, db
from .helpers import blog_render


def config_error_handles(app):
    @app.errorhandler(404)
    def not_found_error(error):
        flash(u'你跑错页面了~~~~~')
        if 'Referer' in request.headers.keys():
            return redirect(request.headers['Referer'])
        else:
            return redirect(url_for('main.index'))

    @app.errorhandler(403)
    def not_found_error(error):
        flash(u'无权操作')
        return redirect(request.headers['Referer'])

    @csrf.error_handler
    def csrf_error(reason):
        return blog_render('error/csrf_error.html', reason=reason), 400

    @app.errorhandler(500)
    def internal_error(error):
        db.session.rollback()
        return blog_render('error/500.html'), 500
